/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package kimo.persistence.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import kimo.persistence.entities.Region;
import kimo.persistence.entities.Municipality;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import kimo.persistence.controllers.exceptions.IllegalOrphanException;
import kimo.persistence.controllers.exceptions.NonexistentEntityException;
import kimo.persistence.controllers.exceptions.PreexistingEntityException;
import kimo.persistence.entities.Prefecture;

/**
 *
 * @author a381u296
 */
public class PrefectureJpaController implements Serializable {

    public PrefectureJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Prefecture prefecture) throws PreexistingEntityException, Exception {
        if (prefecture.getMunicipalityList() == null) {
            prefecture.setMunicipalityList(new ArrayList<Municipality>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Region prefectureRegionId = prefecture.getPrefectureRegionId();
            if (prefectureRegionId != null) {
                prefectureRegionId = em.getReference(prefectureRegionId.getClass(), prefectureRegionId.getRegionId());
                prefecture.setPrefectureRegionId(prefectureRegionId);
            }
            List<Municipality> attachedMunicipalityList = new ArrayList<Municipality>();
            for (Municipality municipalityListMunicipalityToAttach : prefecture.getMunicipalityList()) {
                municipalityListMunicipalityToAttach = em.getReference(municipalityListMunicipalityToAttach.getClass(), municipalityListMunicipalityToAttach.getMunicipalityId());
                attachedMunicipalityList.add(municipalityListMunicipalityToAttach);
            }
            prefecture.setMunicipalityList(attachedMunicipalityList);
            em.persist(prefecture);
            if (prefectureRegionId != null) {
                prefectureRegionId.getPrefectureList().add(prefecture);
                prefectureRegionId = em.merge(prefectureRegionId);
            }
            for (Municipality municipalityListMunicipality : prefecture.getMunicipalityList()) {
                Prefecture oldMunicipalityPrefectureIdOfMunicipalityListMunicipality = municipalityListMunicipality.getMunicipalityPrefectureId();
                municipalityListMunicipality.setMunicipalityPrefectureId(prefecture);
                municipalityListMunicipality = em.merge(municipalityListMunicipality);
                if (oldMunicipalityPrefectureIdOfMunicipalityListMunicipality != null) {
                    oldMunicipalityPrefectureIdOfMunicipalityListMunicipality.getMunicipalityList().remove(municipalityListMunicipality);
                    oldMunicipalityPrefectureIdOfMunicipalityListMunicipality = em.merge(oldMunicipalityPrefectureIdOfMunicipalityListMunicipality);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findPrefecture(prefecture.getPrefectureId()) != null) {
                throw new PreexistingEntityException("Prefecture " + prefecture + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Prefecture prefecture) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Prefecture persistentPrefecture = em.find(Prefecture.class, prefecture.getPrefectureId());
            Region prefectureRegionIdOld = persistentPrefecture.getPrefectureRegionId();
            Region prefectureRegionIdNew = prefecture.getPrefectureRegionId();
            List<Municipality> municipalityListOld = persistentPrefecture.getMunicipalityList();
            List<Municipality> municipalityListNew = prefecture.getMunicipalityList();
            List<String> illegalOrphanMessages = null;
            for (Municipality municipalityListOldMunicipality : municipalityListOld) {
                if (!municipalityListNew.contains(municipalityListOldMunicipality)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Municipality " + municipalityListOldMunicipality + " since its municipalityPrefectureId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (prefectureRegionIdNew != null) {
                prefectureRegionIdNew = em.getReference(prefectureRegionIdNew.getClass(), prefectureRegionIdNew.getRegionId());
                prefecture.setPrefectureRegionId(prefectureRegionIdNew);
            }
            List<Municipality> attachedMunicipalityListNew = new ArrayList<Municipality>();
            for (Municipality municipalityListNewMunicipalityToAttach : municipalityListNew) {
                municipalityListNewMunicipalityToAttach = em.getReference(municipalityListNewMunicipalityToAttach.getClass(), municipalityListNewMunicipalityToAttach.getMunicipalityId());
                attachedMunicipalityListNew.add(municipalityListNewMunicipalityToAttach);
            }
            municipalityListNew = attachedMunicipalityListNew;
            prefecture.setMunicipalityList(municipalityListNew);
            prefecture = em.merge(prefecture);
            if (prefectureRegionIdOld != null && !prefectureRegionIdOld.equals(prefectureRegionIdNew)) {
                prefectureRegionIdOld.getPrefectureList().remove(prefecture);
                prefectureRegionIdOld = em.merge(prefectureRegionIdOld);
            }
            if (prefectureRegionIdNew != null && !prefectureRegionIdNew.equals(prefectureRegionIdOld)) {
                prefectureRegionIdNew.getPrefectureList().add(prefecture);
                prefectureRegionIdNew = em.merge(prefectureRegionIdNew);
            }
            for (Municipality municipalityListNewMunicipality : municipalityListNew) {
                if (!municipalityListOld.contains(municipalityListNewMunicipality)) {
                    Prefecture oldMunicipalityPrefectureIdOfMunicipalityListNewMunicipality = municipalityListNewMunicipality.getMunicipalityPrefectureId();
                    municipalityListNewMunicipality.setMunicipalityPrefectureId(prefecture);
                    municipalityListNewMunicipality = em.merge(municipalityListNewMunicipality);
                    if (oldMunicipalityPrefectureIdOfMunicipalityListNewMunicipality != null && !oldMunicipalityPrefectureIdOfMunicipalityListNewMunicipality.equals(prefecture)) {
                        oldMunicipalityPrefectureIdOfMunicipalityListNewMunicipality.getMunicipalityList().remove(municipalityListNewMunicipality);
                        oldMunicipalityPrefectureIdOfMunicipalityListNewMunicipality = em.merge(oldMunicipalityPrefectureIdOfMunicipalityListNewMunicipality);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = prefecture.getPrefectureId();
                if (findPrefecture(id) == null) {
                    throw new NonexistentEntityException("The prefecture with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Prefecture prefecture;
            try {
                prefecture = em.getReference(Prefecture.class, id);
                prefecture.getPrefectureId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The prefecture with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Municipality> municipalityListOrphanCheck = prefecture.getMunicipalityList();
            for (Municipality municipalityListOrphanCheckMunicipality : municipalityListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Prefecture (" + prefecture + ") cannot be destroyed since the Municipality " + municipalityListOrphanCheckMunicipality + " in its municipalityList field has a non-nullable municipalityPrefectureId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Region prefectureRegionId = prefecture.getPrefectureRegionId();
            if (prefectureRegionId != null) {
                prefectureRegionId.getPrefectureList().remove(prefecture);
                prefectureRegionId = em.merge(prefectureRegionId);
            }
            em.remove(prefecture);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Prefecture> findPrefectureEntities() {
        return findPrefectureEntities(true, -1, -1);
    }

    public List<Prefecture> findPrefectureEntities(int maxResults, int firstResult) {
        return findPrefectureEntities(false, maxResults, firstResult);
    }

    private List<Prefecture> findPrefectureEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Prefecture.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Prefecture findPrefecture(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Prefecture.class, id);
        } finally {
            em.close();
        }
    }

    public int getPrefectureCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Prefecture> rt = cq.from(Prefecture.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
